package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.datacollection.dto.SpecialAddDeductionListDTO;
import com.engine.salary.entity.datacollection.dto.SpecialAddDeductionRecordDTO;
import com.engine.salary.entity.datacollection.param.SpecialAddDeductionImportParam;
import com.engine.salary.entity.datacollection.param.SpecialAddDeductionParam;
import com.engine.salary.entity.datacollection.param.SpecialAddDeductionQueryParam;
import com.engine.salary.entity.datacollection.param.SpecialAddDeductionRecordDeleteParam;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.excel.ExcelPreviewDTO;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.SpecialAddDeductionWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.Nullable;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据采集-专项附加扣除
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author lfc
 **/
@Slf4j
public class SpecialAddDeductionController {

    private SpecialAddDeductionWrapper getSpecialAddDeductionWrapper(User user) {
        return ServiceUtil.getService(SpecialAddDeductionWrapper.class, user);
    }

    /**
     * 数据采集-专项附加扣除列表的高级搜索
     *
     * @return
     */
    @GET
    @Path("/getSearchCondition")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSearchCondition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::getSearchCondition);
    }


    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionQueryParam, PageInfo<SpecialAddDeductionListDTO>>(user).run(getSpecialAddDeductionWrapper(user)::list, queryParam);
    }


    @POST
    @Path("/getSpecialAddDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String getDetailList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionQueryParam param) {
        User user = HrmUserVarify.getUser(request, response);
        Long id = param.getId();
        return new ResponseResult<Long, SpecialAddDeductionRecordDTO>(user).run(getSpecialAddDeductionWrapper(user)::getRecordById, id);
    }

    @POST
    @Path("/getDetailList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSpecialAddDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionQueryParam, PageInfo<SpecialAddDeductionRecordDTO>>(user).run(getSpecialAddDeductionWrapper(user)::getDetailList, queryParam);
    }


    @GET
    @Path("/downloadTemplate")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getAll(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            SpecialAddDeductionQueryParam param = buildParam(request);

            XSSFWorkbook workbook = getSpecialAddDeductionWrapper(user).downloadTemplate(param);
            String fileName = "专项附加扣除导入模板" + LocalDate.now();
            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };
            response.setContentType("application/octet-stream");
            return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            log.error("专项附加扣除导入模板异常", e);
            throw e;
        }
    }


    /**
     * 导出
     *
     * @param
     * @return
     */
    @GET
    @Path("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            SpecialAddDeductionQueryParam param = buildParam(request);

            XSSFWorkbook workbook = getSpecialAddDeductionWrapper(user).export(param);

            String fileName = null;
            try {
                fileName = URLEncoder.encode("专项附加扣除" + LocalDate.now() + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };

            response.setContentType("application/octet-stream");
            return Response.ok(output)
                    .header("Content-disposition", "attachment;filename=" + fileName)
                    .header("Cache-Control", "no-cache").build();
        } catch (Exception e) {
            log.error("专项附加扣除导出异常", e);
            throw e;
        }
    }


    @GET
    @Path("/exportDetail")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportDetail(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            SpecialAddDeductionQueryParam param = buildParam(request);

            XSSFWorkbook workbook = getSpecialAddDeductionWrapper(user).exportDetail(param);

            String fileName = "专项附加扣除明细" + LocalDate.now();
            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };

            response.setContentType("application/octet-stream");
            return Response.ok(output)
                    .header("Content-disposition", "attachment;filename=" + fileName)
                    .header("Cache-Control", "no-cache").build();
        } catch (Exception e) {
            log.error("专项附加扣除明细导出异常", e);
            throw e;
        }

    }

    @Nullable
    private SpecialAddDeductionQueryParam buildParam(HttpServletRequest request) {
        SpecialAddDeductionQueryParam param = new SpecialAddDeductionQueryParam();
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            param.setIds(Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        String keyword = request.getParameter("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            param.setKeyword(keyword);
        }
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            param.setId(Long.valueOf(id));
        }

        String username = request.getParameter("username");
        if (StringUtils.isNotBlank(username)) {
            param.setUsername(username);
        }
        String employeeId = request.getParameter("employeeId");
        if (StringUtils.isNotBlank(employeeId)) {
            param.setEmployeeId(Long.valueOf(employeeId));
        }
        String taxAgentId = request.getParameter("taxAgentId");
        if (StringUtils.isNotBlank(taxAgentId)) {
            param.setTaxAgentId(Long.valueOf(taxAgentId));
        }
        String departmentIds = request.getParameter("departmentIds");
        if (StringUtils.isNotBlank(departmentIds)) {
            param.setDepartmentIds(Arrays.stream(departmentIds.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        String jobNum = request.getParameter("jobNum");
        if (StringUtils.isNotBlank(jobNum)) {
            param.setJobNum(jobNum);
        }
        String idNo = request.getParameter("idNo");
        if (StringUtils.isNotBlank(idNo)) {
            param.setIdNo(idNo);
        }
        String hiredate = request.getParameter("hiredate");
        if (StringUtils.isNotBlank(hiredate)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            List<Date> dates = Arrays.stream(hiredate.split(",")).map(d -> {
                try {
                    return format.parse(d);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(Collectors.toList());
            param.setHiredate(dates);
        }
        String mobile = request.getParameter("mobile");
        if (StringUtils.isNotBlank(mobile)) {
            param.setMobile(mobile);
        }
        String otherTaxExemptDeductionId = request.getParameter("otherTaxExemptDeductionId");
        if (StringUtils.isNotBlank(otherTaxExemptDeductionId)) {
            param.setSpecialAddDeductionId(Long.valueOf(otherTaxExemptDeductionId));
        }
        String hasData = request.getParameter("hasData");
        if (StringUtils.isNotBlank(hasData)) {
            param.setHasData("true".equals(hasData));
        }
        return param;
    }

    @POST
    @Path("/preview")
    @Produces(MediaType.APPLICATION_JSON)
    public String preview(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionImportParam, ExcelPreviewDTO>(user).run(getSpecialAddDeductionWrapper(user)::preview, importParam);
    }

    @POST
    @Path("/importData")
    @Produces(MediaType.APPLICATION_JSON)
    public String importAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionImportParam, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::importData, importParam);
    }

    /**
     * @return String
     * @description 编辑专项附加扣除
     * @author Harryxzy
     * @date 2022/10/26 9:41
     */
    @POST
    @Path("/editData")
    @Produces(MediaType.APPLICATION_JSON)
    public String editOtherDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionParam otherDeductionParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionParam, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::editData, otherDeductionParam);
    }

    /**
     * @return String
     * @description 新建专项附加扣除
     * @author lfc
     */
    @POST
    @Path("/createData")
    @Produces(MediaType.APPLICATION_JSON)
    public String createSpecialAddDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionParam specialAddDeductionParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionParam, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::createData, specialAddDeductionParam);
    }

    /**
     * @return String
     * @description 删除所选专项附加扣除
     * @author lfc
     */
    @POST
    @Path("/deleteSelectData")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteSelectOtherDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionRecordDeleteParam deleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionRecordDeleteParam, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::deleteSelectData, deleteParam);
    }

    /**
     * @return null
     * @description 一键清空专项附加扣除
     * @author lfc
     */
    @POST
    @Path("/deleteAllData")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteAllOtherDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SpecialAddDeductionRecordDeleteParam deductionRecordDeleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SpecialAddDeductionRecordDeleteParam, Map<String, Object>>(user).run(getSpecialAddDeductionWrapper(user)::deleteAllData, deductionRecordDeleteParam);
    }
}
